package net.lcqf.http.config;

import net.lcqf.http.constants.Constants;
import net.lcqf.http.interceptor.TokenInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * 配置拦截器
 * +----------------------------------------------------------------------
 * // | Talk To [ 聊来改善地区金融服务环境，助力企业发展 ]
 * // +----------------------------------------------------------------------
 * // | Copyright (c) 2021-2025 聊来 All rights reserved.
 * // +----------------------------------------------------------------------
 * // | Licensed ( <a href="http://www.apache.org/licenses/LICENSE-2.0">apache</a> )
 * // +----------------------------------------------------------------------
 * // | @Author: 聊来 <18970881148@qq.com>
 * // +----------------------------------------------------------------------
 * // | DateTime: 2025/2/10 14:58
 * // +----------------------------------------------------------------------
 */
@Configuration
public class WebConfig implements WebMvcConfigurer {

    private final TokenInterceptor tokenInterceptor;

    private final TalkConfig config;

    public WebConfig(TokenInterceptor tokenInterceptor, TalkConfig config) {
        this.tokenInterceptor = tokenInterceptor;
        this.config = config;
    }

    /**
     * 拦截器
     * addPathPatterns添加需要拦截的命名空间、excludePathPatterns添加排除拦截命名空间
     *
     * @param registry InterceptorRegistry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(tokenInterceptor)
                .addPathPatterns("/**")
                .excludePathPatterns("/index")
                .excludePathPatterns("/webjars/**")
                .excludePathPatterns("/swagger-resources")
                .excludePathPatterns("/v2/**")
                .excludePathPatterns("/*/api-docs")
                .excludePathPatterns("/doc.html");
    }

    /**
     * 映射服务器资源目录
     * @param registry addResourceHandler 访问路径、addResourceLocations 映射后的真实路径，真实路径必须要以/结尾，切记
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");

        // 本地图片上传路径
        registry.addResourceHandler("/" + Constants.UPLOAD_TYPE_IMAGE + "/**")
                .addResourceLocations("file:" + config.getUploadPath() + "/" + Constants.UPLOAD_TYPE_IMAGE + "/");

        // 本地文件上传路径
        registry.addResourceHandler("/" + Constants.UPLOAD_TYPE_FILE + "/**")
                .addResourceLocations("file:" + config.getUploadPath() + "/" + Constants.UPLOAD_TYPE_FILE + "/");
    }
}